package com.huayue.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.huayue.entity.User;

/**
 * 过滤器
 * 
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        User loginUser = (User)req.getSession().getAttribute("USER");
        String spath = req.getServletPath();
        // 不需要过滤的url
        String[] urls =
            {"/desk", "/login", "/forget.html", "/customer", "/json", ".js", ".css", ".ico", ".jpg", ".png"};
        boolean flag = true;
        for (String str : urls) {
            if (spath.indexOf(str) != -1) {
                flag = false;
                break;
            }
        }
        if (flag) {
            if (loginUser != null) {
                chain.doFilter(request, response);
            } else {
                resp.sendRedirect(req.getContextPath() + "/desk/welcome");
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
